<script lang="ts" setup>
import type { LimbDeviceFirmwareApi } from '#/api';

import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { Button, UploadDragger } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { createDeviceFirmware, updateDeviceFirmware } from '#/api';
import { $t } from '#/locales';

import { useFormSchema } from '../data';

const emits = defineEmits(['success']);

const formData = ref<LimbDeviceFirmwareApi.LimbDeviceFirmware>();

const [Form, formApi] = useVbenForm({
  schema: useFormSchema(),
  showDefaultActions: false,
});

const id = ref();
const [Drawer, drawerApi] = useVbenDrawer({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) return;
    const values = await formApi.getValues();
    drawerApi.lock();
    try {
      if (id.value) {
        const updateData = { ...values };
        await updateDeviceFirmware(id.value, updateData);
      } else {
        await createDeviceFirmware(values);
      }
      emits('success');
      drawerApi.close();
    } catch {
      drawerApi.unlock();
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data =
        drawerApi.getData<LimbDeviceFirmwareApi.LimbDeviceFirmware>();
      formApi.resetForm();
      if (data) {
        formData.value = data;
        id.value = data.id;
        formApi.setValues(data);
      } else {
        id.value = undefined;
      }
    }
  },
});

const getDrawerTitle = computed(() => {
  return formData.value?.id
    ? $t('common.edit', [$t('limb.title')])
    : $t('common.create', [$t('limb.title')]);
});

const fileList = ref([]);

async function resetUploadState() {
  fileList.value = [];
  // await formApi.setValues({
  //   fileData: null,
  // });
}

function handleChange(info) {
  console.log(info);
}

function handleDrop(info) {
  console.log(info);
}

defineExpose({ drawerApi });
</script>

<template>
  <Drawer :title="getDrawerTitle" width="600">
    <Form>
      <template #fileData>
        <v-show v-if="formData?.fileData">
          <span class="text-sm text-gray-500">文件已上传</span>
          <Button type="link" @click="resetUploadState">重新上传</Button>
        </v-show>
        <v-show v-else>
          <UploadDragger
            v-model:file-list="fileList"
            name="file"
            :multiple="false"
            @change="handleChange"
            @drop="handleDrop"
          >
            <p class="ant-upload-text">
              {{ $t('limb.device-firmware.file-upload') }}
            </p>
            <p class="ant-upload-hint">
              {{ $t('limb.device-firmware.file-upload-hint') }}
            </p>
          </UploadDragger>
        </v-show>
      </template>
    </Form>
  </Drawer>
</template>
